﻿using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneLoader : MonoBehaviour
{
    public static SceneLoader instance;
    private AsyncOperation unloadAo;
    private AsyncOperation loadAo;
    public Slider slider;
    private string nextScenen;
    private bool loading = false;
    private void Awake()
    {
        instance = this;
    }
    //游戏最开始的场景就是游戏框架的场景,框架初始化之后再附加其他场景
    public void LoadScene(string nextScenen, string currentScene = null)
    {
        this.nextScenen = nextScenen;
        //卸载当前的场景
        if (currentScene != null)
        {
            unloadAo = SceneManager.UnloadSceneAsync(currentScene);
            unloadAo.completed += p =>
            {
                Debug.Log("卸载完成");
                LoadNextScene();
            };
        }
        else
        {
            LoadNextScene();
        }
    }

    //完成后加载下一个场景
    private void LoadNextScene()
    {
        loading = true;
        slider.gameObject.SetActive(true);
        Debug.Log("加载下一个场景");
        loadAo = SceneManager.LoadSceneAsync(nextScenen, LoadSceneMode.Additive);
        loadAo.completed += LoadEnd;
    }

    private void LoadEnd(AsyncOperation obj)
    {
        print("加载完成");
        slider.gameObject.SetActive(false);
        loading = false;
    }

    private void Update()
    {
        if (loading)
        {
            slider.value = loadAo.progress;
        }
    }
}